/* $RCSFile: UserWinMgmtDB.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/DAL/UserWinMgmtDB.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:28  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Globalization;

using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Settings;

namespace AddonNice.Security
{

	//*********************************************************************
	//
	// UserWinMgmtDB Class
	//
	// The UserWinMgmtDB class encapsulates all data logic necessary to add/delete/query
	// users window mgmt level ( min/max/close )
	//
	//
	//*********************************************************************

	sealed public class UserWinMgmtDB : DBDataStore
	{
		/// <summary>
		/// Save the User's Window Desktop Settings
		/// </summary>
		/// <param name="portalID"></param>
		/// <param name="userID"></param>
		/// <param name="moduleID"></param>
		/// <param name="tabID"></param>
		/// <param name="wstate"></param>
		public void SaveUserDesktop(int portalID, Guid userID, int moduleID, int tabID, AddonNice.BLL.Utils.WindowStateEnum wstate) 
		{
			SqlCommand myCommand = new SqlCommand("dbo.adn_UpdateUserDesktop", myConnection);

			// Mark the Command as a SPROC
			myCommand.CommandType = CommandType.StoredProcedure;

			// Update Parameters to SPROC
			SqlParameter parameterUserID = new SqlParameter("@UserID", SqlDbType.UniqueIdentifier);
			parameterUserID.Value = userID;
			myCommand.Parameters.Add(parameterUserID);

            AddPortalIDParameters(myCommand,portalID);

            AddModuleIDParameters(myCommand,moduleID);

            AddPageIDParameters(myCommand,tabID);
			
			SqlParameter parameterState = new SqlParameter("@WindowState", SqlDbType.SmallInt);
			parameterState.Value = (short)wstate;
			myCommand.Parameters.Add(parameterState);


			// Execute the command
			// CS 10/3/4 error checking
			try
			{

				myConnection.Open();
				myCommand.ExecuteNonQuery();
			}
			catch(Exception exp)
			{
                if ( DBTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"SaveUserDesktop userID : {0}, portalID : {1}, ex : {2}",userID,portalID, exp));
			}
			finally
			{
				if ( myConnection.State == System.Data.ConnectionState.Open )
					myConnection.Close();
			}
		}

		//
		//*********************************************************************
		//
		// DeleteUserDeskTop Method
		//
		// The DeleteUserDeskTop method deletes a specific user desktop from the serDesktop database table.
		//
		//*********************************************************************

		public bool DeleteUserDeskTop(Guid userID, int portalID)
		{
			SqlCommand myCommand				= new SqlCommand("dbo.adn_DeleteUserDesktop", myConnection);
			myCommand.CommandType				= CommandType.StoredProcedure;

			SqlParameter parameterUserID		= new SqlParameter("@UserID", SqlDbType.UniqueIdentifier);
			parameterUserID.Value				= userID;
			myCommand.Parameters.Add(parameterUserID);

            AddPortalIDParameters(myCommand,portalID);
	
			bool results = true;
			try
			{

				myConnection.Open();
				myCommand.ExecuteNonQuery();
				results		=	true;
			}
			catch(Exception exp)
			{
				if ( DBTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"DeleteUserDeskTop userID : {0}, portalID : {1}, ex : {2}",userID,portalID, exp));
				results		=	false;
			}
			finally
			{
				if ( myConnection.State == System.Data.ConnectionState.Open )
					myConnection.Close();
			}
			// Return the status
			return results;
		} // end of DeleteUserDeskTop

		//*********************************************************************
		//
		// GetUserDesktop() Method <a name="GetUserDesktop"></a>
		//
		// The GetUserDesktop method returns a list of the users' desktop envrionment
		//
		// Other relevant sources:
		//     + <a href="GetUserDesktop.htm" style="color:green">GetUserDesktop Stored Procedure</a>
		//
		//*********************************************************************

		public AddonNice.BLL.User.UserLayoutMgr GetUserDesktop(Guid userID, int portalID) 
		{
			AddonNice.BLL.User.UserLayoutMgr ulm		= new AddonNice.BLL.User.UserLayoutMgr();
			SqlCommand myCommand					= new SqlCommand("dbo.adn_GetUserDesktop", myConnection);

			myCommand.CommandType					= CommandType.StoredProcedure;

			SqlParameter parameterUserID			= new SqlParameter("@UserID", SqlDbType.UniqueIdentifier);
			parameterUserID.Value					= userID;
			myCommand.Parameters.Add(parameterUserID);

            AddPortalIDParameters(myCommand,portalID);

            SqlDataReader dr						= null;
			try 
			{
				myConnection.Open();
				dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
				// valid data
				if ( dr != null )
					// populate the data w/ what we want
					populateUserLayoutMgr(dr,ulm);
			} 
			catch(Exception exp)
			{
				if ( DBTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"GetUserDesktop userID : {0}, portalID : {1}, ex : {2}",userID,portalID, exp));
			}
			finally 
			{
				if ( dr != null )
					dr.Close();
				// CS 6/3/4
				if ( myConnection.State == ConnectionState.Open )
					myConnection.Close();

			}
			return ulm;
		} 

		#region Private Methods

		/// <summary>
		/// Populate a User Layout from the Data Reader
		/// </summary>
		/// <param name="dr"></param>
		/// <param name="ulm"></param>
		private void populateUserLayoutMgr(SqlDataReader dr,AddonNice.BLL.User.UserLayoutMgr ulm)
		{
			while (dr.Read())
				ulm.Add(addModuleSettings(dr));
			//do not close here...!!!
		} // end of populateUserLayoutMgr

		/// <summary>
		/// Create the Module Settings 
		/// </summary>
		/// <param name="dr"></param>
		/// <returns></returns>
		private AddonNice.BLL.UserConfig.UserModuleSettings addModuleSettings(SqlDataReader dr)
		{
	
			AddonNice.BLL.UserConfig.UserModuleSettings ums = new AddonNice.BLL.UserConfig.UserModuleSettings();

			try 
			{
				string name			=	string.Empty;
				// iterate over the fields/columns
				for ( int inx=0; inx < dr.FieldCount;++inx)
				{
					// get the values
					if ( !dr.IsDBNull(inx) )
					{
						name				=	dr.GetName(inx).ToLower();
						if ( name[0] == 'm') // module id
							ums.ModuleID	= dr.GetInt32(inx);
						else if ( name[0] == 't' ) // tab id
							ums.PageID		= dr.GetInt32(inx);
						else if ( name[0] == 's' ) // Window State
							ums.State		= (AddonNice.BLL.Utils.WindowStateEnum) dr.GetInt16(inx);
					}
				}
			} 
			catch (System.Exception ex)
			{
				if ( DBTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"addModuleSettings ex : {0}", ex));
				// CS 10/3/4 not fatal throw ex;
			}
			return ums;
		} // end of addModuleSettings

		#endregion

	}

}